package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author lcm
 * @since 2023-07-28
 */
@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final StringRedisTemplate redisTemplate;
    private final RabbitMqHelper mqHelper;

    @Override
    public void addOrRemoveLike(LikeRecordFormDTO likeRecordFormDTO) {
        //1.判断是新增点赞还是取消点赞
        boolean success=likeRecordFormDTO.getLiked() ? like(likeRecordFormDTO) : unlike(likeRecordFormDTO);
        //2.判断是否执行成功
        if(!success){
            return;
        }
        // 3.如果执行成功，统计点赞总数
        Long likedTimes = redisTemplate.opsForSet()
                .size(RedisConstants.LIKE_BIZ_KEY_PREFIX+ likeRecordFormDTO.getBizId());

        if (likedTimes == null) {
            return;
        }
        // 4.缓存点总数到Redis
        redisTemplate.opsForZSet().add(
                RedisConstants.LIKE_COUNT_KEY_PREFIX+likeRecordFormDTO.getBizType(),
                likeRecordFormDTO.getBizId().toString(),
                likedTimes
        );
    }

    //新增点赞后做的处理

    private boolean like(LikeRecordFormDTO likeRecordFormDTO) {
        //1.获取用户id
        Long userId = UserContext.getUser();
        //2.获取key
        String key=RedisConstants.LIKE_BIZ_KEY_PREFIX+likeRecordFormDTO.getBizId();

        Long result = redisTemplate.opsForSet().add(key, userId.toString());

        return result !=null&& result > 0;


    }
    //取消点赞后做的处理
    private boolean unlike(LikeRecordFormDTO likeRecordFormDTO) {
        //1.获取用户id
        Long userId = UserContext.getUser();
        String key=RedisConstants.LIKE_BIZ_KEY_PREFIX+likeRecordFormDTO.getBizId();
        //2.直接移除记录
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());
        return result != null && result > 0;
    }

    @Override
    public Set<Long> queryBatchLikesStatus(List<Long> bizIds) {
        //1.获取用户id
        Long userId = UserContext.getUser();
        //2.批量查询缓存
        final List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(bizIds::get)// 用角标i取bizIds中的对应数据，就是点赞过的id
                .collect(Collectors.toSet());// 收集;
    }

    //定时任务处理点赞总数
    @Override
    public void checkedTimesAndSendMsg(String type, Integer max_bit_size) {

        //根据key从ZSet中获取分数（点赞总数）和值（bizId）
        String key = RedisConstants.LIKE_COUNT_KEY_PREFIX + type;
        Set<ZSetOperations.TypedTuple<String>> tuples = redisTemplate.opsForZSet().popMin(key, max_bit_size);
        //判断是否查出数据
//        if(CollUtils.isEmpty(tuples)){
//            return;
//        }


        //数据转化
        List<Object> list = new ArrayList<>(tuples.size());
        while (CollUtils.isNotEmpty(tuples)){
            for (ZSetOperations.TypedTuple<String> tuple : tuples) {
                String bizId = tuple.getValue();
                Double likedTimes = tuple.getScore();
                if(bizId == null || likedTimes == null){
                    continue;
                }
                list.add(LikedTimesDTO.of(Long.valueOf(bizId),likedTimes.intValue()));
            }
            //发送MQ消息
            mqHelper.send(
                    MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                    StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE,type),
                    list
            );

            tuples=redisTemplate.opsForZSet().popMin(key, max_bit_size);}
    }


}
